﻿namespace Behemoth.SharePoint.Branding {

  using System;
  using System.Collections.ObjectModel;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Text;
  using System.IO;
  using System.Linq;
  using System.Xml.Linq;

  using Behemoth.Configuration;
  using Behemoth.SharePoint.Logging;
  using Behemoth.SharePoint.Branding;

  using Microsoft.SharePoint;
  using Microsoft.SharePoint.Administration;
  using Microsoft.SharePoint.Utilities;

  /// <summary>
  /// 
  /// </summary>
  /// <remarks>
  /// ReceiverAssembly="Behemoth.SharePoint.ARK, Version=1.?.?.?, Culture=neutral, PublicKeyToken=ecab56691def8148"
  /// ReceiverClass="Behemoth.SharePoint.Branding.BrandingFeatureReceiver"
  /// </remarks>
  public class BrandingFeatureReceiver : SPFeatureReceiver {

    #region Logging Code Pattern v2.0

    protected string LOGGING_PRODUCT { get { return "Behemoth"; } }
    protected string LOGGING_CATEGORY { get { return "Branding"; } }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="e"></param>
    public event LoggingEventHandler Logging;

    /// <summary>
    /// Put a method like this in your class that produces log entries
    /// </summary>
    /// <param name="e"></param>
    public void Log(LoggingEventArgs e) {
      // if nobody could be bothered to attach their own events, we should
      // still log things in the default way
      if (Logging == null)
        Logging += new LoggingEventHandler(BehemothLoggingService.Default.Log);
      if (Logging != null)
        Logging(this, e);
    }
    public void Log(string msg) {
      Log(msg, TraceSeverity.Verbose);
    }
    public void Log(string msg, TraceSeverity severity) {
      LoggingEventArgs e = new LoggingEventArgs(LOGGING_CATEGORY, LOGGING_PRODUCT, msg, severity);
      Log(e);
    }
    public void Log(Exception ex) {
      LoggingEventArgs e = new LoggingEventArgs(LOGGING_CATEGORY, LOGGING_PRODUCT, ex);
      Log(e);
    }

    #endregion

    private BrandingProperties brandProps;

    private void EnsureProperties(SPFeatureReceiverProperties properties) {
      Log("Invoking EnsureProperties.");
      if (brandProps == null)
        brandProps = new BrandingProperties(properties);
      else if (brandProps.InitStatus != Status.Initialized)
        throw new Exception("property reader is not initialized. Can't continue.");
      Log("Leaving EnsureProperties.");
    }

    public override void FeatureActivated(SPFeatureReceiverProperties properties) {
      EnsureProperties(properties);
      if (brandProps.Site == null)
        return;
      SPWeb web = brandProps.Web; //RootWeb
      MasterPageTools mpt = new MasterPageTools();
      mpt.Logging += Logging;
      if (brandProps.EnableResetMasterOnActivation) {
        Log("Invoking ProcessWeb for Activation.");
        try {
          mpt.ProvisionMasterPages(brandProps, web, true, true);
        } catch (Exception ex) {
          Log(ex);
        }
        Log("ProcessWeb for Activation Completed.");
      }
      // TODO SP2010 uploading a Thmx file is simpler but we have not implemented this yet in SharePoint 2010
      /*
        try {
          web.Theme
            ThemeTools.ModifySPTheme(
                ThemeTools.ModificationType.Add,
                brandProps.ThemeName,
                brandProps.ThemeDisplayName,
                brandProps.ThemeDescription,
                brandProps.ThemePreviewImageName);
        } catch (Exception ex) {
            Log(string.Format("Exception while modifying system files for theme name '{0}'.", brandProps.ThemeName), TraceSeverity.Exception);
            Log(ex);
        }
          */
      try {
        if (brandProps.ApplyTheme) {
          //This is the oldschool way
          //web.ApplyTheme(brandProps.ThemeName);
          ReadOnlyCollection<ThmxTheme> managedThemes = null;
          managedThemes = ThmxTheme.GetManagedThemes(web.Site);
          foreach (ThmxTheme theme in managedThemes) {
            if (string.Compare(theme.Name, brandProps.ThemeName, true) == 0) {
              theme.ApplyTo(web, false); // TODO what is the correct bool value here?
              break;
            }
          }
        }
      } catch (Exception ex) {
        Log(string.Format("Exception while applying theme name '{0}'.", brandProps.ThemeName), TraceSeverity.Unexpected);
        Log(ex);
      }
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
      EnsureProperties(properties);
      if (brandProps.Site == null)
        return;

      SPWeb web = brandProps.Web; // RootWeb
      MasterPageTools mpt = new MasterPageTools();
      mpt.Logging += Logging;
      if (brandProps.EnableDeleteGalleryFilesOnDeactivation) {
        try {
          mpt.DeleteMasterPageFiles(brandProps);
        } catch (Exception ex) {
          Log(ex);
        }
      }
      if (brandProps.EnableResetMasterOnDeactivation) {
        Log("Invoking ProcessWeb for Deactivation.");
        try {
          mpt.ProvisionMasterPages(brandProps, web, true, true);
        } catch (Exception ex) {
          Log(ex);
        }
        Log("ProcessWeb for Deactivation Completed.");
      }
      if (brandProps.ApplyTheme) {
        string themeName = "None"; // Behemoth.SharePoint.Branding.ThemeTools.DEFAULT_THEME_NAME;
        try {
          // TODO SP2010 there is a new fangled way to do this in SharePoint 2010
          web.ApplyTheme(themeName);
        } catch (Exception ex) {
          Log(string.Format("Exception while applying theme name '{0}'.", themeName), TraceSeverity.Unexpected);
          Log(ex);
        }
      }
    }

    public override void FeatureInstalled(SPFeatureReceiverProperties properties) {
      // TODO SP2010 uploading a Thmx file is simpler but we have not implemented this yet in SharePoint 2010
      /*
      try {
            EnsureProperties(properties);
            ThemeTools.ModifySPTheme(
                ThemeTools.ModificationType.Add, 
                brandProps.ThemeName, 
                brandProps.ThemeDisplayName,
                brandProps.ThemeDescription, 
                brandProps.ThemePreviewImageName);
        } catch (Exception ex) {
            Log(ex);
        }
       */
    }

    public override void FeatureUninstalling(SPFeatureReceiverProperties properties) {
      EnsureProperties(properties);
      // TODO SP2010 uploading a Thmx file is simpler but we have not implemented this yet in SharePoint 2010
      /*
      try {
          ThemeTools.ModifySPTheme(
              ThemeTools.ModificationType.Remove, 
              brandProps.ThemeName, 
              brandProps.ThemeDisplayName,
              brandProps.ThemeDescription, 
              brandProps.ThemePreviewImageName);
      } catch (Exception ex) {
          Log(ex);
      }
     */
    }

  } // class
} // namespace

